package cn.com.pansky.action.bank;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.com.pansky.sdk.API;
import cn.com.pansky.util.AppUtils;
import cn.com.pansky.util.RequestUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * 建行退款异步通知
 * @author Administrator
 *
 */
public class RefundBackEnd extends HttpServlet {

	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	};

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.setStatus(HttpServletResponse.SC_OK);// 响应清算平台通知
		// 获取通知参数
		Map<String, String> reqMap = RequestUtils.getReqMap(req);
		System.out.println("接收到退款异步通知报文:" + reqMap.toString());
		// 根据商户号获取秘钥
		JSONArray array = API.getAAE051OrSignkey(reqMap.get("merId"));
		JSONObject obj = JSONObject.parseObject(array.get(0).toString());
		String signkey = obj.getString("BAE300");
		//签名验证
		boolean validate = AppUtils.validate(reqMap, signkey, reqMap.get("charset"));
		String orderNumber = reqMap.get("orderNumber"); // 订单号
		if(orderNumber != null && !orderNumber.equals("")) {
			// 获取订单号，退货订单号去掉最后一位R
			orderNumber = orderNumber.substring(0, orderNumber.length()-1);
		}
		JSONObject object = new JSONObject();
		object.put("AAZ288", orderNumber);
		object.put("AAZ295", "JH");
		if (validate) {
			// 签名验证通过
			if ("1".equals(reqMap.get("state"))) {
				// 订单退款成功
				System.out.println("建行对账订单退款成功.");
				API.UpdSysRA22(orderNumber, reqMap.get("qid"), "1");
//				refund.updOrderAAE356(object, true);
			} else if ("2".equals(reqMap.get("state"))) {
				// 订单退款失败
				System.out.println("建行对账订单退款失败.");
				API.UpdSysRA22(orderNumber, reqMap.get("qid"), "2");
//				refund.updOrderAAE356(object, false);
			}
		} else {
			// 签名验证失败
			System.out.println("建行对账退款异步通知签名验证失败.");
			API.UpdSysRA22(orderNumber, reqMap.get("qid"), "2");
//			refund.updOrderAAE356(object, false);
		}
	}

}
